package com.txl.tvluancher;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class JSInterface {
    private static JSInterface jsInterface;
    private WebView webView;
    private String appJson;
    private List<AppModel> settingAppArray = new ArrayList<>();

    public static JSInterface getInstance() {
        if (jsInterface == null) {
            jsInterface = new JSInterface();
        }
        return jsInterface;
    }

    private JSInterface() {
    }

    public void setWebView(WebView webView) {
        this.webView = webView;
    }

    @JavascriptInterface
    public String getSelfPkName() {
        return MyApp.getApp().getPackageName();
    }

    @JavascriptInterface
    public String loadApps() {
        List<AppModel> appModels = new ArrayList<>();
        try {
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = MyApp.getApp().getPackageManager().queryIntentActivities(mainIntent, 0);

            PackageManager pm = MyApp.getApp().getPackageManager();

            settingAppArray.clear();
            for (ResolveInfo info : resolveInfos) {
                AppModel appModel = new AppModel();
                appModel.setName(info.loadLabel(pm).toString());
                appModel.setPkm(info.activityInfo.packageName);
                appModel.setAkm(info.activityInfo.name);
                PackageInfo pk = null;

                pk = MyApp.getApp().getPackageManager().getPackageInfo(info.activityInfo.packageName, 0);
                //是否系统预装
                boolean sys = (pk.applicationInfo.flags & pk.applicationInfo.FLAG_SYSTEM) > 0;
                appModel.setSys(sys);
                appModels.add(appModel);

                if(sys && appModel.getPkm().contains("setting")){
                    settingAppArray.add(appModel);
                }
            }

            appJson = new Gson().toJson(appModels);
            return appJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @JavascriptInterface
    public String loadAppIcon(String pkm) {
        if(TextUtils.isEmpty(pkm)){
            return "";
        }
        Log.i(JSInterface.class.getSimpleName(), "loadAppIcon:" + pkm);
        try {
            PackageManager pm = MyApp.getApp().getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(pkm, PackageManager.GET_META_DATA);
            Drawable icon = pm.getApplicationIcon(applicationInfo);
            Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
            String iconBase64 = Base64.encodeToString(BitmapToBytes(bitmap), Base64.NO_WRAP | Base64.NO_PADDING); //| Base64.URL_SAFE
            return iconBase64;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 以返回流的形式加载图标，webview加载速度比上面转base64快上不少
     * @param pkm
     * @return
     */
    public InputStream loadIcon(String pkm) {
        if(TextUtils.isEmpty(pkm)){
            return null;
        }
        Log.i(JSInterface.class.getSimpleName(), "loadAppIcon:" + pkm);
        try {
            PackageManager pm = MyApp.getApp().getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(pkm, PackageManager.GET_META_DATA);
            Drawable icon = pm.getApplicationIcon(applicationInfo);
            Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(BitmapToBytes(bitmap));
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    @JavascriptInterface
    public void gotoSetting(){
        try{
            Intent intent =  new Intent(Settings.ACTION_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApp.getApp().startActivity(intent);
        }catch (Exception e){
            startSetting();
        }
    }

    public void stateChange(final String type, final String value){
        Log.i(JSInterface.class.getSimpleName(), "stateChange type:"+type+",value:"+value);
        HomeActivity.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(webView == null ){
                    return;
                }
                JSInterface.this.webView.loadUrl("javascript:stateChange('"+type+"','" + value+ "')");
            }
        });
    }

    /**
     * 判断当前网络有没有联网
     * 并且判断是有线还是无线
     *
     * 0:无网络连接
     * 1：有线网络
     * 2：无线网络
     * 3: 未知网络
     *
     * @return
     */
    @JavascriptInterface
    public int getNetMode() {
       int code = 0;
        try{
            ConnectivityManager connectivityManager = (ConnectivityManager) MyApp.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info == null) {
                code = 0;
            }else{
                boolean iscon = info.isAvailable();
                if (!iscon) {
                    code = 0;
                }else{
                    if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        code = 1;
                    } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                        code = 2;
                    } else {
                        code = 3;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        stateChange("network",code+"");
        return code;
    }

    @JavascriptInterface
    public void gotoWifiSeting(){
        try{
            Intent intent =  new Intent(Settings.ACTION_WIFI_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApp.getApp().startActivity(intent);
        }catch (Exception e){
            Toast.makeText(MyApp.getApp(),"打开WIFI设置失败",Toast.LENGTH_SHORT).show();
        }
    }


    private void startSetting(){
        if(settingAppArray == null){
            return;
        }
        for(AppModel appModel : settingAppArray){
            startActivity(appModel.getPkm(),appModel.getAkm());
        }
    }

    @JavascriptInterface
    public void startActivity(String pkName, String className) {
        if(TextUtils.isEmpty(pkName) || TextUtils.isEmpty(className)){
            return;
        }

        try{
            ComponentName componet = new ComponentName(pkName, className);
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setComponent(componet);
            intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApp.getApp().startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private byte[] BitmapToBytes(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
}
